package com.example.goodrubish;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.example.goodrubish.API.Okhttp_work;
import com.example.goodrubish.Fragment.SearchFragment;
import com.example.goodrubish.Garbage.Garbage_adapter;
import com.example.goodrubish.Garbage.Garbage_list;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class Search extends AppCompatActivity {

    private ListView garbageList_View;
    public static int garbage_id;

    private JSONObject search_result= SearchFragment.Search_JSON;      //用于接收SearchFragment中的搜索结果
    private List<Garbage_list> garbageList=new ArrayList<>();

    private EditText text_search;
    private Button btn_search;
    String url_garbage="http://api.tianapi.com/txapi/lajifenlei/index?key=8edca382d393d0c5f84996d0e8946b96&word=";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ActionBar actionbar=getSupportActionBar();
        if(actionbar!=null){
            actionbar.hide();
        }

        text_search = findViewById(R.id.text_searchb);
        btn_search = findViewById(R.id.btn_searchb);

        try {
            init_garbage_list();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Garbage_adapter adapter=new Garbage_adapter(Search.this, R.layout.garbage_item, garbageList);
        ListView listView=findViewById(R.id.search_listview);
        listView.setAdapter(adapter);

        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                init_search();
            }
        });

        garbageList_View=findViewById(R.id.search_listview);
        garbageList_View.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                garbage_id=i;
                Intent intent=new Intent();
                //跳转到细节页面
                intent.setClass(Search.this, Detail.class);
                startActivity(intent);
            }
        });

    }
    private JSONObject make_the_JSON(int i) throws JSONException {            //用于将JSON转换为字符串数组
        JSONArray newslist=search_result.getJSONArray("newslist");
        String[] name=new String[newslist.length()];
        String newslistString=new String();
        JSONObject the_garbage_JSON = new JSONObject();       //具体某一项的json ，可以通过getstring获得其中具体的项
        newslistString=newslist.getString(i);
        the_garbage_JSON=new JSONObject(newslistString);
//        name[i]=the_garbage_JSON.getString("name");
        return the_garbage_JSON;
    }


    private void init_garbage_list() throws JSONException {
        JSONArray newslist=search_result.getJSONArray("newslist");
        for(int i=0;i<newslist.length();i++){
            Garbage_list the_garbage=new Garbage_list(make_the_JSON(i));
            garbageList.add(the_garbage);
        }
    }

    public void init_search() {
        View view = getWindow().peekDecorView();
        if (view != null) {//这里是网络访问的代码，获取服务
            InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
        initData_search();
    }

    Handler handler_search=new Handler(new Handler.Callback() {//首先通过handler发送信息
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 0:
                    Toast.makeText(Search.this,"网络错误",Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    String json=(String)msg.obj;
                    try{
                        SearchFragment.Search_JSON=new JSONObject(json);
                        Intent intent=new Intent();
                        intent.setClass(Search.this, Search.class);
                        startActivity(intent);		//进行页面跳转
                        finish();
                        break;
                    }catch (JSONException e){
                        e.printStackTrace();
                    }
                default:
                    throw new IllegalStateException("Unexpected value: " + msg.what);
            }
            return false;
        }
    });

    private void initData_search(){
        String data=text_search.getText().toString();
        if(TextUtils.isEmpty(data)){//如果内容为空，弹出toast消息，不为空则执行164行以后的代码
            Toast.makeText(Search.this,"垃圾名称不能为空！",Toast.LENGTH_SHORT).show();
        }
        else{
            Okhttp_work.OkHttpGet(url_garbage+data, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String content=response.body().string();
                    Message message=new Message();
                    message.what=1;
                    message.obj=content;
                    handler_search.sendMessageDelayed(message,1000);
                }
            });
        }
    }
}